/*
* RemoveComments
*
* r2
*
* GNU General Public License v3.0
*/

package com.acme;

import java.io.*;
import java.nio.charset.*;

// TODO: [VY] Please, move message to final static field.
public class RemoveComments {
	private final static String errorMessage = "Error:";
	private final static String usageMessage = "Usage: java RemoveComments <input file> <output file>";
	private final static String inputError = "Input file can't be opened";
	private final static String outputError = "Output file can't be opened";
	private final static String fileError = "File operation error";
	
	private static void error(String str) {
		System.out.println(errorMessage + str);
		System.exit(0);
	}
	
	public static void main(String[] args) {
		FileInputStream in = null;
		FileWriter out = null;
		
		if(args.length < 2) {
			System.out.println(usageMessage);
			return;
		}
		
		try {
			in = new FileInputStream(new File(args[0]));
		} catch(Exception ex) {
			error(inputError);
		}
		
		try {
			out = new FileWriter(args[1]);
		} catch(Exception ex) {
			error(outputError);
		}
		
		try {
			InputStreamReader reader = new InputStreamReader(in, Charset.defaultCharset());
			BufferedWriter writer = new BufferedWriter(out);
			
			int ch, prevChar = 0;
			while((ch = reader.read()) != -1) {
				if(ch == '/') {
					if(prevChar == '/') {
						while((ch != '\n') && (ch != -1)) {
							ch = reader.read();
						}
						writer.write('\n');
					}
				} else if(ch == '*') {
					if(prevChar == '/') {
						do{
							while((ch != '*') && (ch != -1)) {
								ch = reader.read();
							}
							ch = reader.read();
						} while ((ch != '/') && (ch != -1));
					}
				} else {
					writer.write(ch);
				}
				prevChar = ch;
			}
			writer.flush();
		} catch(Exception ex) {
			error(fileError);
		}
	}
}
